package com.bruce.codeFactory.Thread;

import java.util.*;

/**
 * @author luotuan
 * @Description  模拟一个小型的线程池使用，控制当前可执行的线程数
 * @create 2019-02-19 22:23
 **/
public class CaptureService {

    final static private LinkedList<Control> CONTROLS = new LinkedList<>();

    private static final int MAXSIZE = 5;

    public static void main(String[] args) {
        List<Thread> worker = new ArrayList<>();
        Arrays.asList("M1", "M2", "M3", "M4", "M5", "M6", "M7", "M8", "M9", "M10").stream()
                .map(CaptureService::createThread)
                .forEach(t -> {
                    t.start();
                    worker.add(t);
                });
        worker.stream().forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Optional.of("All of capture worker finished").ifPresent(System.out::println);
    }

    private static Thread createThread(String name) {
        return new Thread(() -> {
            Optional.of("The worker [ " + Thread.currentThread().getName() + " ] begin capture data").ifPresent(System.out::println);
            synchronized (CONTROLS) {
                while (CONTROLS.size() > MAXSIZE) {
                    try {
                        CONTROLS.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                CONTROLS.addLast(new Control());
            }
            Optional.of("The worker [ " + Thread.currentThread().getName() + " ] is working...").ifPresent(System.out::println);
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (CONTROLS) {
                Optional.of("The worker [ " + Thread.currentThread().getName() + " ] END capture data..").ifPresent(System.out::println);
                CONTROLS.removeFirst();
                CONTROLS.notifyAll();
            }
        }, name);
    }

    private static class Control {

    }
}
